#include<iostream>
#include<string>
#include<ctime>
#include<cassert>
#include<unistd.h>
#include"Sock.hpp"
#include"Protocol.hpp"

std::string opers = "+-*/%=^";

void Usage(const std::string& proc)
{
    std::cout << "Usage:" << proc << "  clientip clientport" << std::endl;
}

int main(int argc,char* argv[])
{
    if(argc !=3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Sock sock;
    sock.Socket();


    bool ret = sock.Connect(serverport,serverip);
    if(!ret) exit(-1);

    int cnt = 1;
    srand(time(nullptr));
    while(cnt <= 10)
    {
        std::cout << "==============第" << cnt << "次请求计算==============" << std::endl;
        int x = rand()%100;
        usleep(123);
        int y = rand()%100;
        usleep(432);
        char op = opers[rand()%opers.size()];
        Request req(x,y,op);

        std::string content;
        req.Serialize(&content);
        std::string package = Encode(content);
        write(sock.Fd(),package.c_str(),package.size());
        std::cout << package;

        char buffer[1024];
        std::string inbuff_stream;
        ssize_t n = read(sock.Fd(),buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            inbuff_stream = buffer;
            std::string info;
            Decode(inbuff_stream,&info);

            Response resp;
            resp.DeSerialize(info);
            std::cout << "result:" << resp.result << " ,code:" << resp.code << std::endl;
        }
        else if(n == 0) break;
        else    break;
        std::cout << "================================================" << std::endl;
        cnt++;
        sleep(1);
    }

    return 0;
}